import {Box, TextField} from "@mui/material";
import {ChangeEventHandler, FC, useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";
import AppProvider from "../../../sources/AppProvider.ts";
import {AlertColor} from "@mui/material/Alert/Alert";
import DGConnect from "../../../sources/DGConnect.ts";
import DGToast from "../../../components/DGToast.tsx";
import DGDialogLayout from "../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGTextView from "../../../components/DGTextView.tsx";
import DGDrawerLayout from "../../../components/DGDrawerLayout/DGDrawerLayout.tsx";

interface ChangeNameProps {
    state: boolean,
    close: () => void,
}

interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}


const ChangeName: FC<ChangeNameProps> = ({state, close}) => {
    // 获取程序上下文
    const App = AppProvider.useAppContext();
    // 路由跳转
    const router = useNavigate();
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});
    // 设置加载状态
    const [loading, setLoading] = useState(false);
    // 设置错误信息
    const [error, setError] = useState({state: false, text: ""});
    // 设置昵称信息
    const [name, setName] = useState("");


    // 关闭函数
    const handleClose = (id: number) => {
        // 判断是否加载状态
        if (!loading) {
            // 关闭面板弹窗
            close();
            // 后退路由
            if (id === 1) router(-1);
        }
    }


    // 更改时函数
    const handleChange: ChangeEventHandler<HTMLInputElement> = e => {
        // 清除错误信息
        setError({state: false, text: ""});
        // 更新昵称
        setName(e.target.value);
    }


    // 提交函数
    const handleSubmit = () => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 判断昵称是否和登陆的相同
        if (App!.info && App!.info["name"] === name) return setError({state: true, text: "昵称没有任何修改！"});
        // 开始加载
        setLoading(true);
        // 发起更改昵称请求
        DGConnect.POST(JSON.stringify({info: "changeName", name: name}), result => {
            // 关闭加载
            setLoading(false);
            // 返回错误信息
            if (result['data']['code'] !== 200) {
                return setError({state: true, text: result['data']['message'] + "错误码：" + result["data"]["code"]});
            }
            // 刷新用户数据
            App!.setUserInfo(result['data']['result']);
            // 提示修改完成
            setToast({state: true, severity: "success", text: '昵称更改成功！'});
            // 关闭弹窗
            setTimeout(() => handleClose(1), 500);
        }, error => {
            // 关闭加载
            setLoading(false);
            // 提示更改失败
            setError({state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error['stack']});
        });
    }


    useEffect(() => {
        // 加载昵称信息
        if (App && App!.info) setName(String(App!.info['name']));
        // 清除错误信息
        setError({state: false, text: ""});
    }, [App, App?.info, state]);


    const ContentView = (<>
        {/* 未登录提示语 */}
        {!App!.info && <DGTextView Body Bold>您当前未登陆账户，服务不可用！</DGTextView>}
        {/* 已登录 */}
        {App!.info && <Box>
            {/* 提示语 */}
            <DGTextView Body Bold>来为您的账户设置一个好听的昵称吧！留空将会生成随机昵称！</DGTextView>
            {/* 输入框 */}
            <TextField
                type="text" label="请输入昵称：" margin="dense" variant="standard" disabled={loading}
                defaultValue={name} onChange={handleChange} error={error.state} helperText={error.text} fullWidth/>
        </Box>}
    </>);

    return (<Box>
        {/* Toast 组件 */}
        <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            submit={App!.info ? {name: "确定", click: handleSubmit} : undefined} load={loading}
            title="更改昵称" state={state} close={() => handleClose(1)} PANEL AUTO>
            {ContentView}
        </DGDialogLayout>
        {/* DGDrawerLayout 样式 */}
        <DGDrawerLayout
            submit={App!.info ? {name: "确定", click: handleSubmit} : undefined} load={loading}
            title="更改昵称" state={state} close={() => handleClose(1)} flex="bottom" PANEL AUTO>
            {ContentView}
        </DGDrawerLayout>
    </Box>);
}

export default ChangeName;